package org.advanced.aqs;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author John.zhang
 * @version Id: DataImportThread, v 1.0 2020/12/10 19:49 ZhiYong Exp $
 * 所有子任务都完成的前提下再去进行主任务，有点类似于CountDownLatch
 */
public class DataImportThread extends Thread {

    private String path;

    private CyclicBarrier cyclicBarrier;

    public DataImportThread(String path, CyclicBarrier cyclicBarrier) {
        this.path = path;
        this.cyclicBarrier = cyclicBarrier;
    }

    @Override
    public void run() {
        System.out.println("开始导入" + path);
        try {
            try {
                //设置超时时间
                cyclicBarrier.await(10, TimeUnit.SECONDS);
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
    }


    public static class CyclicBarrierA extends Thread {
        @Override
        public void run() {
            System.out.println("开始数据汇总");
        }


        /**
         * 如果没有足够的现成来调用await,就会导致所有现成阻塞
         * 可以设置timeout
         * 也可以重置计数 cyclicBarrier.reset();
         * @param args
         */
        public static void main(String[] args) {
            CyclicBarrier cyclicBarrier = new CyclicBarrier(3, new CyclicBarrierA());
            new DataImportThread("A", cyclicBarrier).start();
            new DataImportThread("B", cyclicBarrier).start();
            new DataImportThread("C", cyclicBarrier).start();
            //三个线程执行完做一个汇总
        }
    }


}
